package com.star.links;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.TextView;


import com.star.links.Service.Impl.PlayServiceImpl;
import com.star.links.Service.PlayService;
import com.star.links.configure.PlayConfigure;
import com.star.links.views.Block;
import com.star.links.views.MyView;

import java.util.Timer;
import java.util.TimerTask;


public class GameFragment extends Fragment implements View.OnClickListener, PopupMenu.OnMenuItemClickListener {

    private View view;

    // 游戏配置对象
    private PlayConfigure config;
    // 游戏业务逻辑接口
    private PlayService playService;
    //菜单按钮
    private Button menuButton;
    // 游戏界面
    private MyView myView;
    // 失败后弹出的对话框
    private AlertDialog.Builder failDialog;
    // 游戏胜利后的对话框
    private AlertDialog.Builder victoryDialog;
    // 记录是否处于游戏状态
    private boolean isPlaying;
    //难度系数
    private int difficultyLevel=0;
    // 记录已经选中的方块
    private Block selected = null;
    //定时器
    private Timer timer=new Timer();
    //记录剩余时间
    private int remainingTime;
    //展示剩余时间
    private TextView timeTextView;
    //消息处理
    private Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case 0x123:
                    timeTextView.setText("剩余时间： " +remainingTime);
                    remainingTime--;
                    // 时间小于0, 游戏失败
                    if (remainingTime < 0)
                    {
                        stopTimer();
                        // 更改游戏的状态
                        isPlaying=false;
                        failDialog.show();
                        return;
                    }
                    break;
            }
        }
    };




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化界面
        Bundle bundle=this.getArguments();
        if(null!=bundle){
            difficultyLevel=bundle.getInt("difficultyLevel");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(view==null) {
            view= inflater.inflate(R.layout.fragment_game, container, false);
        }
        init();
        myView.startGame();
        startTime(PlayConfigure.DEFAULT_TIME);
        return view;
    }
    //设置游戏难度
    public void setDifficulty(int difficulty){
        config.setDifficulty(difficulty);
    }


    @Override
    public void onPause() {
        // 暂停游戏
        stopTimer();
        super.onPause();
    }


    @Override
    public void onResume() {
        // 如果处于游戏状态中
        if (isPlaying)
        {
            // 以剩余时间重写开始游戏
            startTime(remainingTime);
        }
        super.onResume();
    }

    // 初始化游戏的方法
    private void init()
    {
        config = new PlayConfigure(8, 9, 0, 0, this.getActivity());
        //设置游戏难度
        config.setDifficulty(difficultyLevel);
        // 得到游戏区域对象
        myView = view.findViewById(R.id.myView);
        //获取菜单按钮
        menuButton=view.findViewById(R.id.menuButton);
        //获取展示剩余时间的文本框
        timeTextView=view.findViewById(R.id.timeText);
        //获取服务接口
        playService = new PlayServiceImpl(this.config);
        myView.setPlayService(playService);
        menuButton.setOnClickListener(this);
//        //为重排按钮设置监听事件
//        resetButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                playService.reset();
//                myView.postInvalidate();
//            }
//        });






        // 为游戏区域的触碰事件绑定监听器
        this.myView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(motionEvent.getAction()==MotionEvent.ACTION_DOWN){
                    myViewTouchDown(motionEvent);
                }
                if (motionEvent.getAction()==MotionEvent.ACTION_UP){
                    myViewTouchUp(motionEvent);
                }
                return true;
            }
        });

        // 初始化游戏失败的对话框
        failDialog = createDialog("Fail", "时间到了！！！", R.drawable.ic_fail);
        failDialog.setPositiveButton("重排", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int which)
            {
                playService.reset();
                myView.postInvalidate();
                startTime(PlayConfigure.DEFAULT_TIME/2);
            }
        });
        failDialog.setNegativeButton("重开", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int which)
                {
                    startTime(PlayConfigure.DEFAULT_TIME);
                }
            });

        // 初始化游戏胜利的对话框
        victoryDialog = createDialog("Victory", "游戏胜利！ 重新开始",
                R.drawable.ic_victory).setPositiveButton("确定",
                new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        startTime(PlayConfigure.DEFAULT_TIME);
                    }
                });
    }


    //按下游戏区域的处理方法
    private void myViewTouchDown(MotionEvent event){
        Block[][] blocks=playService.getBlocks();
        float x = event.getX();
        float y = event.getY();
        Block currentBlock=playService.findBlock(x,y);
        if (currentBlock==null){
            return;
        }
//            this.myView.setSelectedBlock(block);
        if(this.selected==null){
            this.selected=currentBlock;
            this.myView.postInvalidate();
            return;
        }
        if(this.selected!=null)
        {
            boolean flag=this.playService.isLink(this.selected,currentBlock);
            if(!flag){
                this.selected=currentBlock;
                this.myView.postInvalidate();
            }else {
                handleSuccessLink(this.selected,currentBlock,blocks);
            }
        }
    }


    // 松开游戏区域的处理方法
    private void myViewTouchUp(MotionEvent event)
    {
        this.myView.postInvalidate();
    }

    // 以gameTime作为剩余时间开始或恢复游戏
    private void startTime(int remainingTime)
    {
        // 如果之前的timer还未取消，取消timer
        if (this.timer != null)
        {
            stopTimer();
        }
        // 重新设置游戏时间
        this.remainingTime = remainingTime;
        // 如果游戏剩余时间与总游戏时间相等，即为重新开始新游戏
        if(remainingTime == PlayConfigure.DEFAULT_TIME)
        {
            // 开始新的游戏游戏
            myView.startGame();
        }
        isPlaying = true;
        this.timer = new Timer();
        // 定时任务，调用schedule方法后延迟0毫秒执行run方法，随后每隔1000毫秒执行一次run方法
        this.timer.schedule(new TimerTask()
        {
            public void run()
            {
                handler.sendEmptyMessage(0x123);
            }
        }, 0, 1000);
        // 将选中方块设为null。
        this.selected = null;
    }

    private void stopTimer(){
        //停止计时器
        this.timer.cancel();
        this.timer=null;
    }

    private void handleSuccessLink( Block preBlock, Block currentBlock, Block[][] blocks)
    {


        this.myView.postInvalidate();
        // 将两个Piece对象从数组中删除
        blocks[preBlock.getIndexX()][preBlock.getIndexY()] = null;
        blocks[currentBlock.getIndexX()][currentBlock.getIndexY()] = null;
        // 将选中的方块设置null。
        this.selected = null;
        // 判断是否还有剩下的方块, 如果没有, 游戏胜利
        if (!this.playService.hasBlocks())
        {
            //游戏胜利
            this.victoryDialog.show();
            //停止计时器
            stopTimer();
            // 更改游戏状态
            isPlaying = false;
        }

    }

    //弹出菜单
    @Override
    public void onClick(View view) {
        PopupMenu popupMenu=new PopupMenu(getActivity(),view);
        popupMenu.inflate(R.menu.game_menu);
        popupMenu.setOnMenuItemClickListener(this);
        popupMenu.show();
    }
    @Override
    public boolean onMenuItemClick(MenuItem menuItem) {
        switch (menuItem.getItemId()){
            case R.id.resetButton:
                playService.reset();
                myView.postInvalidate();
                break;
            case R.id.restart:
                startTime(PlayConfigure.DEFAULT_TIME);
            default:
                break;
        }
        return false;
    }

    // 创建对话框的工具方法
    private AlertDialog.Builder createDialog(String title, String message,
                                             int imageResource)
    {
        return new AlertDialog.Builder(this.getActivity()).setTitle(title)
                .setMessage(message).setIcon(imageResource);
    }

}